import os
import json
import logging
from datetime import datetime
from flask import request

# 配置文件路径
UPLOAD_FOLDER = "uploads"
config_path = os.path.join(UPLOAD_FOLDER, "page/config.json")

# 修改读取配置文件函数，确保能处理新的下载计数结构
def get_config():
    try:
        with open(config_path, 'r') as f:
            return json.load(f)
    except FileNotFoundError:
        return {}


# 保存配置文件
def save_config_file(config):
    try:
        with open(config_path, 'w') as f:
            f.write(config)
        return {"code": 0, "msg": "Config saved successfully"}
    except Exception as e:
        return {"code": 500, "msg": f"Failed to save config: {str(e)}"}

def get_directory_size(directory):
    """递归计算目录的总大小（字节）"""
    total_size = 0
    try:
        for item in os.listdir(directory):
            item_path = os.path.join(directory, item)
            # 跳过.part文件
            if '.part' in item:
                continue
            if os.path.isfile(item_path):
                total_size += os.path.getsize(item_path)
            elif os.path.isdir(item_path):
                # 递归计算子目录大小
                total_size += get_directory_size(item_path)
    except Exception as e:
        print(f"计算目录 {directory} 大小时出错: {e}")
    return total_size

def get_file_list(UPLOAD_FOLDER):
    page = int(request.args.get('page', 1))
    limit = int(request.args.get('limit', 10))
    folder = os.path.join(UPLOAD_FOLDER, request.args.get('folder', ''))
    filter_name = request.args.get('filter_name', '').lower()
    filter_type = request.args.get('filter_type', '')
    start = (page - 1) * limit

    files = []
    for filename in os.listdir(folder):
        # 屏蔽 page 目录
        if filename == 'page':
            continue
        # 屏蔽包含 .part 的文件
        if '.part' in filename:
            continue
        file_path = os.path.join(folder, filename)
        if not os.path.exists(file_path):
            continue

        isfile = os.path.isfile(file_path)
        file_type = os.path.splitext(filename)[1][1:] if isfile else "文件夹"
        mtime = os.path.getmtime(file_path)
        upload_time = datetime.fromtimestamp(mtime).strftime('%Y-%m-%d %H:%M:%S')
        
        config = get_config()
        download_count = config.get('download_counts', {}).get(filename, 0)
        
        # 计算文件/文件夹大小
        if isfile:
            file_size = os.path.getsize(file_path)
        else:
            # 对于文件夹，计算其包含的所有文件总大小
            file_size = get_directory_size(file_path)
        
        # 根据大小自动转换单位并格式化
        if file_size >= 1024 * 1024 * 1024:  # 大于等于1GB
            size_value = file_size / (1024 * 1024 * 1024)
            size_str = f"{round(size_value, 2)}G"
        elif file_size >= 1024 * 1024:  # 大于等于1MB
            size_value = file_size / (1024 * 1024)
            size_str = f"{round(size_value, 2)}M"
        else:  # 小于1MB，用KB显示
            size_value = file_size / 1024
            size_str = f"{round(size_value, 2)}K"

        # 应用筛选条件
        if filter_name and filter_name not in filename.lower():
            continue
        if filter_type and file_type != filter_type:
            continue
            
        files.append({
            'name': os.path.relpath(file_path, folder),
            'type': file_type,
            'upload_time': upload_time,
            'download_count': download_count,
            'isfile': isfile,
            'path': file_path,
            'size': size_str,
            'mtime': mtime  # 添加时间戳用于排序
        })

    # 排序逻辑：文件夹在前，按修改时间倒序
    files.sort(key=lambda x: (x['isfile'], -x['mtime']))

    total = len(files)
    files = files[start:start + limit]

    return {"code": 0, "msg": "", "total": total, "data": files}


# 升级程序
def handle_upgrade_program(request, app):
    try:
        # 读取配置文件
        with open(config_path, 'r') as f:
            config = json.load(f)
        # 获取升级路径
        upgrade_path = config.get('upgrade_path')
        if not upgrade_path:
            return json.dumps({"code": 400, "msg": "Upgrade path not found in config"}), 400

        file = request.files.get('file')
        if not file:
            return json.dumps({"code": 400, "msg": "No file found in the request"}), 400

        # 确保升级程序目录存在
        if not os.path.exists(upgrade_path):
            os.makedirs(upgrade_path)

        file_path = os.path.join(upgrade_path, file.filename)
        file.save(file_path)

        return json.dumps({"code": 0, "msg": "Program upgrade successful"})

    except Exception as e:
        logging.error(f"Program upgrade failed: {str(e)}")
        return json.dumps({"code": 500, "msg": f"Program upgrade failed: {str(e)}"}), 500